import { login, getInfo, getUserProfile, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken() || '', // token
  userInfo: {} // 用户信息
}

const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    // 设置token
    setToken(newToken)
  },

  removeToken(state) {
    state.token = ''
    // 移除token
    removeToken()
  },

  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },

  // 移除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 发送login请求
  async loginRequest(context, data) {
    const res = await login(data)
    context.commit('setToken', res.data)
  },

  // 获取用户信息并存储到 state > userInfo 中
  async getUserInfo(context) {
    const res = await getUserProfile()
    const userInfo = await getUserDetailById(res.data.userId)
    // console.log(userInfo)
    context.commit('setUserInfo', { ...res.data, ...userInfo.data })
  },

  // 退出
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

